package service

import (
	"fitness/internal/dao"
	"fitness/internal/entity/system"
	"fitness/pkg/utils"
	"fitness/pkg/utils/R"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
)

type MenuService struct {
	SysUserDao *dao.SysUserDao
	SysMenuDao *dao.SysMenuDao
	Log        *zap.Logger
}

func NewMenuService(SysUserDao *dao.SysUserDao,
	SysMenuDao *dao.SysMenuDao,
	Log *zap.Logger) *MenuService {
	return &MenuService{
		SysUserDao: SysUserDao,
		SysMenuDao: SysMenuDao,
		Log:        Log,
	}
}

func (menusService *MenuService) GetMenus(c *gin.Context) {
	var menuQuery system.MenuQuery
	err := c.ShouldBindQuery(&menuQuery)
	if err != nil {
		menusService.Log.Error("获取菜单失败", zap.Error(err))
		c.JSON(http.StatusOK, R.ReturnFailMsg("获取菜单失败"))
		return
	}
	list, err := menusService.SysMenuDao.GetMenus(menuQuery)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(list))
}

func (menusService *MenuService) RoutesV1(c *gin.Context) {
	//根据角色id查询角色菜单
	roleStr := c.GetString("role_id")
	if roleStr != "" {
		roleList := strings.Split(roleStr, ",")
		routes, err := menusService.SysMenuDao.ListRoutes(roleList)
		if err != nil {
			menusService.Log.Error("获取路由失败", zap.Error(err))
			c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
			return
		}
		c.JSON(http.StatusOK, R.ReturnSuccess(routes))
	} else {
		c.JSON(http.StatusOK, R.ReturnFailMsg("尚未给当前用户分配角色"))
		return
	}
}

func (menusService *MenuService) ListMenuOptions(c *gin.Context) {
	var err error
	var routes []utils.Option[uint64]
	routes, err = menusService.SysMenuDao.ListMenuOptionsWithTenantId()
	if err != nil {
		c.JSON(http.StatusInternalServerError, R.ReturnSuccess(err))
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(routes))
}

func (menusService *MenuService) GetMenuForm(c *gin.Context) {
	menuIdStr := c.Param("menuId")
	// 尝试将字符串转换为整数
	menuId, err := strconv.ParseUint(menuIdStr, 10, 64)
	if err != nil {
		// 如果转换失败，返回错误响应
		c.JSON(http.StatusOK, "Invalid ID")
		return
	}
	form, err := menusService.SysMenuDao.GetMenuForm(menuId)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(form))
}

func (menusService *MenuService) DeleteMenu(c *gin.Context) {
	idStr := c.Param("id")
	b, err := menusService.SysMenuDao.DeleteMenu(idStr)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(b))
}

func (menusService *MenuService) UpdateMenu(c *gin.Context) {
	var menuForm system.MenuForm
	err := c.ShouldBindJSON(&menuForm)
	if err != nil {
		menusService.Log.Error("转换失败", zap.Error(err))
		c.JSON(http.StatusOK, "修改参数失败")
		return
	}
	result, err := menusService.SysMenuDao.SaveMenu(menuForm)
	if err != nil {
		c.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	c.JSON(http.StatusOK, R.ReturnSuccess(result))
}
